<template>
  <div class="app-container">
    <!-- 表格-条件筛区域  -->
    <div class="filter-container">
      <el-input placeholder="请输入名称" v-model="searchParam.SEARCH_LIKE_name" style="width: 200px;"
                class="filter-item"
                @keyup.enter.native="handleFilter"/>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter"> 搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
                 @click="handleCreate"> 新增
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="info" icon="el-icon-refresh"
                 @click="handleRefresh"> 刷新首页缓存
      </el-button>
    </div>

    <!-- 表格-内容区域 -->
    <el-table v-loading="listLoading" :key="tableKey" :data="tableList" border fit highlight-current-row
              style="width: 100%;">
      <el-table-column v-for="column in columns" :key="column.prop"
                       :prop="column.prop"
                       :label="column.label"
                       :width="column.width"
                       :align="column.align?column.align:'center'"
                       :min-width="column.minWidth"
                       :sortable="column.sortable"
                       :fixed="column.fixed"
                       :type="column.type" :formatter="column.formatter">
        <template slot-scope="scope">
          <!-- 行内显示图片 -->
          <img v-if="column.imgFlag==true"
               :src=" scope.row[column.prop].indexOf('http') >-1 ?  scope.row[column.prop] : ( CMBASE.baseFileContext + scope.row[column.prop] ) "
               width="60" height="60" class="img"/>
          <!-- 行内显示开关按钮 -->
          <el-switch v-else-if="column.switchFlag==true" v-model="scope.row[column.prop]" :active-value="1"
                     :inactive-value="0" disabled/>
          <!-- 行内显示tag标签 -->
          <span v-else-if="column.tagFlag==true">
                        <span v-for="item in column.tagFormatter" :key="item.value">
                            <el-tag v-if="item.value==scope.row[column.prop]" :type="item.type">{{ item.text }}</el-tag>
                        </span>
                    </span>
          <!-- 行内格式自定义 -->
          <span v-else-if="column.formatter"> {{ column.formatter(scope.row) }}</span>
          <!--默认显示文本-->
          <span v-else>{{ scope.row[column.prop] }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="340" class-name="small-padding">
        <template slot-scope="scope">
          <el-button type="warning" size="mini" @click="showDicValueInfo( scope.row )"> 字典值维护
          </el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)"> 编辑</el-button>
          <el-button type="danger" size="mini" @click="handleDelete(scope.row)"> 删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 表格-页脚区域 -->
    <pagination v-show="tableTotal>0" :total="tableTotal" :page.sync="pageRequest.pageNum"
                :limit.sync="pageRequest.pageSize" @pagination="getList"/>

    <!--新增编辑界面-->
    <el-dialog :title="operation?'新增':'编辑'" width="45%" top="5vh" :visible.sync="dialogFormVisible"
               :close-on-click-modal="false">
      <el-form :model="dataForm" label-width="140px" :rules="dataFormRules" ref="dataForm" style="width: 80%">

        <el-form-item label="数据字典名称" prop="name">
          <el-input v-model="dataForm.name" auto-complete="off" placeholder="请输入数据字典名称"/>
        </el-form-item>
        <el-form-item label="数据字典编码" prop="code">
          <el-input v-model="dataForm.code" auto-complete="off" placeholder="请输入数据字典编码"/>
        </el-form-item>
        <el-form-item label="数据字典类型" prop="dicType">
          <el-radio-group v-model="dataForm.dicType">
            <el-radio-button label="1">列表</el-radio-button>
            <el-radio-button label="2">单条</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序号" prop="orderNo">
          <el-input-number v-model="dataForm.orderNo" :min="1"  label="排序号"></el-input-number>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="dataForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click.native="closeDialog()">取消</el-button>
        <el-button size="mini" @click.native="saveFormData()" :loading="editLoading" type="primary">提交
        </el-button>
      </div>
    </el-dialog>


    <!--sku属性key对应value列表-->
    <el-dialog :title="dicCodeType === 1? '字典值维护-列表' : '字典值维护-单条'" :visible.sync="getValueListVisible"
               :close-on-click-modal="false" width="70%"
               top="10vh">
      <div v-if="dicCodeType === 2">

        <el-form :model="dataFormValue" label-width="140px" :rules="dataFormRulesValue" ref="dataFormValue"
                 style="width: 90%">

          <el-form-item label="排序号码" prop="oderNo">
            <el-input-number v-model="dataFormValue.oderNo" :min="1" :max="1000"
                             label="排序号码"></el-input-number>
          </el-form-item>
          <el-form-item label="数据字典类型" prop="dicType">
            <el-radio-group v-model="dataFormValue.dicType">
              <el-radio-button :label="1">富文本</el-radio-button>
              <el-radio-button :label="2">JSON串</el-radio-button>
              <el-radio-button :label="3">图片</el-radio-button>
              <el-radio-button :label="4">文本</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="字典值内容" prop="value">
            <tinymce v-if="dataFormValue.dicType===1 && getValueListVisible" :height="300" v-model="dataFormValue.value" id='tinymce'
                     :value="dataFormValue.value"></tinymce>
            <el-input v-if="dataFormValue.dicType===2 && getValueListVisible" type="textarea" v-model="dataFormValue.value"
                      rows="20"></el-input>
            <cm-upload-img v-if="dataFormValue.dicType===3 && getValueListVisible" v-model="dataFormValue.value"></cm-upload-img>
            <el-input v-if="dataFormValue.dicType===4 && getValueListVisible" type="textarea" v-model="dataFormValue.value"
                      rows="20"></el-input>
          </el-form-item>
        </el-form>
      </div>

      <div v-else>

        <!-- 表格-条件筛区域  -->
        <div class="filter-container">
          <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
                     @click="handleCreateValue"> 新增
          </el-button>
        </div>
        <!-- 表格-内容区域 -->
        <el-table v-loading="listLoading2" :key="1" :data="tableListValue" border fit highlight-current-row
                  style="width: 100%;">

          <el-table-column v-for="column in columnsValue" :key="column.prop"
                           :prop="column.prop"
                           :label="column.label"
                           :width="column.width"
                           :align="column.align?column.align:'center'"
                           :min-width="column.minWidth"
                           :sortable="column.sortable"
                           :fixed="column.fixed"
                           :type="column.type" :formatter="column.formatter">
            <template slot-scope="scope">
              <!-- 行内显示图片 -->
              <img v-if="column.imgFlag==true"
                   :src=" scope.row[column.prop].indexOf('http') >-1 ?  scope.row[column.prop] : ( CMBASE.baseFileContext + scope.row[column.prop] ) "
                   width="60" height="60" class="img"/>
              <!-- 行内显示开关按钮 -->
              <el-switch v-else-if="column.switchFlag==true" v-model="scope.row[column.prop]"
                         :active-value="1"
                         :inactive-value="0" disabled/>
              <!-- 行内显示tag标签 -->
              <span v-else-if="column.tagFlag==true">
                                <span v-for="item in column.tagFormatter" :key="item.value">
                                    <el-tag v-if="item.value==scope.row[column.prop]"
                                            :type="item.type">{{ item.text }}</el-tag>
                                </span>
                            </span>
              <!-- 行内格式自定义 -->
              <span v-else-if="column.formatter"> {{ column.formatter(scope.row) }}</span>
              <!--默认显示文本-->
              <span v-else>{{ scope.row[column.prop] }}</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" width="240" class-name="small-padding">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="handleUpdateValue(scope.row)"> 编辑</el-button>
              <el-button type="danger" size="mini" @click="handleDeleteValue(scope.row)"> 删除</el-button>
            </template>
          </el-table-column>
        </el-table>

      </div>

      <div slot="footer" class="dialog-footer" v-if="dicCodeType!==1">
        <el-button size="mini" @click.native=" getValueListVisible = false ">关闭</el-button>
        <el-button :loading="editLoadingValue" size="mini" type="primary" @click.native="saveFormDataValue(0)">
          提交
        </el-button>
      </div>
      <div slot="footer" class="dialog-footer" v-else>
        <el-button size="mini" @click.native=" getValueListVisible = false ">关闭</el-button>
      </div>

    </el-dialog>

    <!--新增编辑列表二级value页面-->
    <el-dialog title="字典值维护-列表" :visible.sync="dialogFormVisibleValue"
               :close-on-click-modal="false"
               width="70%" top="5vh">
      <el-form :model="dataFormValue" label-width="140px" :rules="dataFormRulesValue" ref="dataFormValue"
               style="width: 90%">
        <el-form-item label="字典值名称" prop="code">
          <el-input v-model="dataFormValue.name" auto-complete="off" placeholder="请输入字典值名称"/>
        </el-form-item>
        <el-form-item label="数据字典类型" prop="dicType">
          <el-radio-group v-model="dataFormValue.dicType">
            <el-radio-button :label="1">富文本</el-radio-button>
            <el-radio-button :label="2">JSON串</el-radio-button>
            <el-radio-button :label="3">图片</el-radio-button>
            <el-radio-button :label="4">文本</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="字典值内容" prop="value">
          <tinymce v-if="dataFormValue.dicType===1 && dialogFormVisibleValue" :height="300" v-model="dataFormValue.value" id='tinymce'
                   :value="dataFormValue.value"></tinymce>
          <el-input v-if="dataFormValue.dicType===2 && dialogFormVisibleValue" type="textarea" v-model="dataFormValue.value"
                    rows="20"></el-input>
          <cm-upload-img v-if="dataFormValue.dicType===3 && dialogFormVisibleValue" v-model="dataFormValue.value"></cm-upload-img>
          <el-input v-if="dataFormValue.dicType===4 && dialogFormVisibleValue" type="textarea" v-model="dataFormValue.value"
                    rows="20"></el-input>
        </el-form-item>
        <el-form-item label="排序号码" prop="oderNo">
          <el-input-number v-model="dataFormValue.oderNo" :min="1"  label="排序号码"></el-input-number>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="dataFormValue.remark"></el-input>
        </el-form-item>
      </el-form>


      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click.native=" dialogFormVisibleValue = false ">关闭</el-button>
        <el-button :loading="editLoadingValue" size="mini" type="primary" @click.native="saveFormDataValue()">提交
        </el-button>
      </div>

    </el-dialog>


  </div>
</template>
<script>
import Pagination from '@/components/Pagination' // 分页栏信息
import Tinymce from '@/components/CmUEditor'
import CmUploadImg from '@/components/CmUpload'
export default {
  name: 'system-dic',
  components: {
    Pagination, Tinymce, CmUploadImg
  },
  directives: {},
  filters: {},
  data() {
    return {
      tableKey: 0,
      tableList: [],//表格数据源
      tableTotal: 0,//表格总条数数据
      listLoading: true,
      pageRequest: {pageNum: 1, pageSize: 10,},
      searchParam: {SEARCH_LIKE_name: ''},
      dialogFormVisible: false,//默认不显示弹出框
      operation: true, // true:新增, false:编辑
      editLoading: false,//保存表单时loading框
      columns: [
        {prop: 'name', label: '数据字典名称', sortable: false},
        {prop: 'code', label: '数据字典编码', sortable: false},
        {
          prop: 'dicType', label: '数据字典类型', sortable: false, tagFlag: true,
          tagFormatter: [
            {text: '列表', value: 1, type: 'success'},
            {text: '单条', value: 2, type: 'success'}
          ]
        },
        {prop: 'orderNo', label: '排序号', sortable: false},
        {prop: 'createTime', label: '创建时间', sortable: false},
      ],
      fileList: [],
      // 新增编辑界面数据
      dataForm: {},
      //表单检验规则
      dataFormRules: {
        name: [{required: true, message: '请输入数据字典名称', trigger: 'blur'}],
        code: [{required: true, message: '请输入数据字典编码', trigger: 'blur'}],
        dicType: [{required: true, message: '请输入数据字典类型', trigger: 'blur'}],
        orderNo: [{required: true, message: '请输入排序号', trigger: 'blur'}],
      },

      operationValue: '',

      // 字典项信息列表
      getValueListVisible: false,
      listLoading2: false,
      tableListValue: [],//表格数据源
      tableTotalValue: 0,//表格总条数数据
      searchParamValue: {SEARCH_EQ_did: ''},
      columnsValue: [
        {prop: 'name', label: '字典值名称', sortable: false},
        {
          prop: 'dicType', label: '数据字典类型', sortable: false, tagFlag: true,
          tagFormatter: [
            {text: '富文本', value: 1, type: 'info'},
            {text: 'JSON串', value: 2, type: 'success'},
            {text: '图片', value: 3, type: 'warning'},
            {text: '文本', value: 4, type: 'info'}
          ]
        },
        {prop: 'value', label: '字典值', sortable: false},
        {prop: 'oderNo', label: '排序号码', sortable: false},
        {prop: 'createTime', label: '创建时间', sortable: false},
      ],
      dicCodeType: 0,
      dialogFormVisibleValue: false,
      dataFormValue: {},
      dataFormRulesValue: {
        name: [{required: true, message: '请输入字典内容名称', trigger: 'blur'}],
        dicType: [{required: true, message: '请输入字典内容类型', trigger: 'blur'}],
        value: [{required: true, message: '请输入字典内容', trigger: 'blur'}],
        oderNo: [{required: true, message: '请输入排序号', trigger: 'blur'}],
      },
      editLoadingValue: false,
    }
  },
  created() {
    this.getList();
  },
  methods: {


    //获取表格数据
    getList() {
      this.pageRequest.searchParam = this.searchParam
      this.listLoading = true
      //【API请求】----获取表格列表数据
      this.$api.getSysDicCodeList(this.pageRequest).then(response => {
        this.tableList = response.data.content
        this.tableTotal = response.data.total
        this.listLoading = false;
      }).catch((res) => {
        console.log('请求异常', res);
        this.listLoading = false;
      })
    },
    //表格数据筛选
    handleFilter() {
        this.pageRequest = {
            pageNum: 1,
            pageSize: 10,
        }
      this.getList()
    },
    //【按钮点击】--- 弹出新增表单
    handleCreate() {
      this.operation = true;
      this.initDataForm();
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.editLoading = false;
      })
    },
    handleRefresh(){
      this.$api.refreshHomeInfo().catch((res) => {
        console.log('刷新失败', res);
      })
      this.getList()
    },
    //【按钮点击】--- 弹出编辑表单
    handleUpdate(row) {
      this.operation = false;
      this.dataForm = Object.assign({}, row)
      //显示编辑菜单
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.editLoading = false;
      })
    },

    //【按钮点击】---展示数据字典值列表
    showDicValueInfo(row) {

      this.listLoading2 = true
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      this.dicCodeType = row.dicType
      //【API请求】----获取表格列表数据
      this.searchParamValue.SEARCH_EQ_did = row.id
      this.$api.getSysDicValueList({
        pageNum: 1,
        pageSize: 1000,
        searchParam:{
          SEARCH_EQ_did: row.id
        }
      }).then(response => {

        this.tableListValue = response.data.content
        this.tableTotalValue = response.data.total


        if (this.dicCodeType !== 1) {
          this.initDataFormValue()
          if (this.tableListValue.length > 0) {
            this.dataFormValue = Object.assign({}, this.tableListValue[0])
          }
          this.dataFormValue.did = this.searchParamValue.SEARCH_EQ_did
        }
        this.getValueListVisible = true;


        this.listLoading2 = false;
        loading.close();
      }).catch((res) => {
        console.log('请求异常', res);
        this.listLoading2 = false;
        loading.close();
      })

    },

    // --- 弹出编辑表单
    handleCreateValue() {
      this.dialogFormVisibleValue = true
      this.initDataFormValue()
      this.dataFormValue.did = this.searchParamValue.SEARCH_EQ_did
      this.$nextTick(() => {
        this.$refs['dataFormValue'].clearValidate()
        this.editLoadingValue = false
      })
    },

    // --- 弹出编辑表单
    handleUpdateValue(row) {
      this.dataFormValue = Object.assign({}, row)
      // 显示编辑菜单
      this.dialogFormVisibleValue = true
      this.$nextTick(() => {
        this.$refs['dataFormValue'].clearValidate()
        this.editLoadingValue = false
      })
    },

    saveFormDataValue(flag) {

      this.$refs['dataFormValue'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.editLoadingValue = true
        // 【API请求】----保存数据
        this.$api.saveSysDicValue(this.dataFormValue).then(() => {
          this.editLoadingValue = false// 关闭loading框
          this.dialogFormVisibleValue = false// 关闭表单页面
          this.initDataFormValue()// 重置表单数据
          var id = this.searchParamValue.SEARCH_EQ_did

          //是否显示第一层弹出层
          if (flag !== 0) {
            this.showDicValueInfo({id: id, dicType: this.dicCodeType})// 重新获取表格数据
          } else {
            this.getValueListVisible = false;
          }

          this.$notify({title: '成功', message: '保存成功', type: 'success', duration: 2000})
        })
      })


    },


    // 【属性值 按钮点击】---删除行
    handleDeleteValue(row) {
      this.$confirm('确认删除该记录吗？', '提示', {}).then(() => {
        // 【API请求】---- 删除数据
        this.$api.deleteSysDicValue({ids: row.id}).then(() => {
          this.$message({message: '操作成功', type: 'success'})
          var id = this.searchParamValue.SEARCH_EQ_did
          this.showDicValueInfo({id: id, dicType: this.dicCodeType})// 重新获取表格数据
        })
      }).catch(() => {
      })
    },

    initDataFormValue() {
      this.dataFormValue = {
        id: '',
        did: '',
        value: '',
        code: '',
        oderNo: 1,
        remark: '',
        createTime: '',
        createUser: '',
        updateTime: '',
        updateUser: '',
      };
    },


    //保存表单数据
    saveFormData() {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false;
        }
        this.editLoading = true;
        //【API请求】----保存数据
        this.$api.saveSysDicCode(this.dataForm).then(() => {
          this.editLoading = false;//关闭loading框
          this.dialogFormVisible = false;//关闭表单页面
          this.initDataForm();//重置表单数据
          this.getList();//重新获取表格数据
          this.$notify({title: '成功', message: '保存成功', type: 'success', duration: 2000})
        })
      })
    },
    //【按钮点击】---删除行
    handleDelete(row) {
      this.$confirm('确认删除该记录吗？', '提示', {}).then(() => {
        //【API请求】---- 删除数据
        this.$api.deleteSysDicCode({ids: row.id}).then(() => {
          this.$message({message: '操作成功', type: 'success'})
          this.pageRequest.pageNum = 1
          this.getList();
        })
      }).catch(() => {
        this.$message({message: '操作失败', type: 'error'})
      });
    },
    //初始化表单数据，重新渲染
    initDataForm() {
      this.dataForm = {
        id: '',
        pid: '',
        name: '',
        code: '',
        dicType: '',
        orderNo: '',
        remark: '',
        createTime: '',
        createUser: '',
        updateTime: '',
        updateUser: '',
      };
    },
    //关闭表单弹出框
    closeDialog() {
      this.$refs['dataForm'].resetFields();
      this.dialogFormVisible = false
    },

  }


}
</script>







